#!/usr/bin/env python3
"""
专业SVG生成器 - 参考K717效果
生成包含完整坐标系统、网格、顶点坐标表的工程图纸风格SVG
"""

import math
from typing import List, Tuple, Optional
from enhanced_ploop_processor import Vertex

def generate_professional_svg(vertices: List[Vertex], title: str = "PLOOP Profile", height_mm: float = 5700.0) -> str:
    """
    生成专业的工程图纸风格SVG
    参考K717的效果，包含完整的坐标系统和顶点坐标表
    """
    if not vertices:
        return "<svg></svg>"
    
    # SVG画布尺寸
    canvas_width = 1000
    canvas_height = 800
    margin = 60
    
    # 计算数据边界
    x_coords = [v.x for v in vertices]
    y_coords = [v.y for v in vertices]
    
    min_x, max_x = min(x_coords), max(x_coords)
    min_y, max_y = min(y_coords), max(y_coords)
    
    # 计算绘图区域
    plot_width = canvas_width - 2 * margin - 300  # 为坐标表留空间
    plot_height = canvas_height - 2 * margin - 80  # 为标题和轴标签留空间
    
    # 坐标变换
    x_range = max_x - min_x
    y_range = max_y - min_y
    
    if x_range == 0: x_range = 1
    if y_range == 0: y_range = 1
    
    def transform_x(x):
        return margin + (x - min_x) / x_range * plot_width
    
    def transform_y(y):
        return canvas_height - margin - 40 - (y - min_y) / y_range * plot_height
    
    # 开始生成SVG
    svg_content = f'''<svg width="{canvas_width}" height="{canvas_height}" viewBox="0 0 {canvas_width} {canvas_height}" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="{canvas_width}" height="{canvas_height}" opacity="1" fill="#FFFFFF" stroke="none"/>
<text x="{canvas_width//2}" y="25" dy="0.76em" text-anchor="middle" font-family="Arial" font-size="16" opacity="1" fill="#000000">
{title} (高度: {height_mm}mm, 带FRADIUS圆弧)
</text>'''
    
    # 生成网格线
    svg_content += generate_grid_lines(margin, plot_width, plot_height, canvas_height)
    
    # 生成坐标轴和刻度
    svg_content += generate_axes_and_ticks(margin, plot_width, plot_height, canvas_height, min_x, max_x, min_y, max_y)
    
    # 生成主路径
    svg_content += generate_main_path(vertices, transform_x, transform_y)
    
    # 生成顶点标记
    svg_content += generate_vertex_markers(vertices, transform_x, transform_y)
    
    # 生成FRADIUS圆弧标记
    svg_content += generate_fradius_markers(vertices, transform_x, transform_y)
    
    # 生成顶点坐标表
    svg_content += generate_coordinate_table(vertices, canvas_width)
    
    svg_content += '</svg>'
    
    return svg_content

def generate_grid_lines(margin: int, plot_width: float, plot_height: float, canvas_height: int) -> str:
    """生成网格线"""
    grid_content = ""
    
    # 垂直网格线
    for i in range(9):
        x = margin + i * plot_width / 8
        grid_content += f'<line opacity="0.1" stroke="#000000" stroke-width="1" x1="{x:.0f}" y1="{canvas_height - margin - 40}" x2="{x:.0f}" y2="{margin + 40}"/>\n'
    
    # 水平网格线
    for i in range(8):
        y = margin + 40 + i * plot_height / 7
        grid_content += f'<line opacity="0.1" stroke="#000000" stroke-width="1" x1="{margin}" y1="{y:.0f}" x2="{margin + plot_width}" y2="{y:.0f}"/>\n'
    
    # 加粗的主网格线
    for i in range(0, 9, 2):
        x = margin + i * plot_width / 8
        grid_content += f'<line opacity="0.2" stroke="#000000" stroke-width="1" x1="{x:.0f}" y1="{canvas_height - margin - 40}" x2="{x:.0f}" y2="{margin + 40}"/>\n'
    
    for i in range(0, 8, 2):
        y = margin + 40 + i * plot_height / 7
        grid_content += f'<line opacity="0.2" stroke="#000000" stroke-width="1" x1="{margin}" y1="{y:.0f}" x2="{margin + plot_width}" y2="{y:.0f}"/>\n'
    
    return grid_content

def generate_axes_and_ticks(margin: int, plot_width: float, plot_height: float, canvas_height: int, 
                           min_x: float, max_x: float, min_y: float, max_y: float) -> str:
    """生成坐标轴和刻度"""
    axes_content = ""
    
    # 主坐标轴
    left_x = margin - 1
    bottom_y = canvas_height - margin - 40 + 1
    
    axes_content += f'<polyline fill="none" opacity="1" stroke="#000000" stroke-width="1" points="{left_x},{margin + 40} {left_x},{bottom_y} "/>\n'
    axes_content += f'<polyline fill="none" opacity="1" stroke="#000000" stroke-width="1" points="{margin},{bottom_y} {margin + plot_width},{bottom_y} "/>\n'
    
    # X轴刻度和标签
    for i in range(9):
        x = margin + i * plot_width / 8
        x_value = min_x + i * (max_x - min_x) / 8
        
        axes_content += f'<text x="{x:.1f}" y="{canvas_height - margin - 25}" dy="0.76em" text-anchor="middle" font-family="sans-serif" font-size="10" opacity="1" fill="#000000">\n'
        axes_content += f'{x_value:.1f}\n'
        axes_content += f'</text>\n'
        axes_content += f'<polyline fill="none" opacity="1" stroke="#000000" stroke-width="1" points="{x:.1f},{bottom_y - 5} {x:.1f},{bottom_y} "/>\n'
    
    # Y轴刻度和标签
    for i in range(8):
        y = canvas_height - margin - 40 - i * plot_height / 7
        y_value = min_y + i * (max_y - min_y) / 7
        
        axes_content += f'<text x="{margin - 10}" y="{y:.1f}" dy="0.5ex" text-anchor="end" font-family="sans-serif" font-size="10" opacity="1" fill="#000000">\n'
        axes_content += f'{y_value:.1f}\n'
        axes_content += f'</text>\n'
        axes_content += f'<polyline fill="none" opacity="1" stroke="#000000" stroke-width="1" points="{margin - 5},{y:.1f} {margin},{y:.1f} "/>\n'
    
    # 轴标签
    axes_content += f'<text x="20" y="{(margin + 40 + canvas_height - margin - 40) / 2}" dy="0.76em" text-anchor="middle" font-family="sans-serif" font-size="10" opacity="1" fill="#000000" transform="rotate(270, 20, {(margin + 40 + canvas_height - margin - 40) / 2})">\n'
    axes_content += 'Y (mm)\n'
    axes_content += '</text>\n'
    
    axes_content += f'<text x="{(margin + margin + plot_width) / 2}" y="{canvas_height - 10}" dy="-0.5ex" text-anchor="middle" font-family="sans-serif" font-size="10" opacity="1" fill="#000000">\n'
    axes_content += 'X (mm)\n'
    axes_content += '</text>\n'
    
    return axes_content

def generate_main_path(vertices: List[Vertex], transform_x, transform_y) -> str:
    """生成主路径"""
    if not vertices:
        return ""
    
    path_d = "M "
    for i, vertex in enumerate(vertices):
        x, y = transform_x(vertex.x), transform_y(vertex.y)
        if i == 0:
            path_d += f"{x:.2f} {y:.2f}"
        else:
            path_d += f" L {x:.2f} {y:.2f}"
    
    return f'<path d="{path_d}" fill="none" opacity="1" stroke="#0000FF" stroke-width="2"/>\n'

def generate_vertex_markers(vertices: List[Vertex], transform_x, transform_y) -> str:
    """生成顶点标记和编号"""
    markers_content = ""
    
    for i, vertex in enumerate(vertices):
        x, y = transform_x(vertex.x), transform_y(vertex.y)
        
        # 顶点圆圈
        markers_content += f'<circle cx="{x:.0f}" cy="{y:.0f}" r="3" opacity="1" fill="#FF0000" stroke="white" stroke-width="1"/>\n'
        
        # 顶点编号
        text_x = x + (10 if i % 2 == 0 else -10)
        text_y = y + (15 if i % 3 == 0 else -8)
        anchor = "start" if i % 2 == 0 else "end"
        
        markers_content += f'<text x="{text_x:.0f}" y="{text_y:.0f}" font-family="Arial" font-size="10" font-weight="bold" fill="#000000" stroke="white" stroke-width="0.5" text-anchor="{anchor}">{i}</text>\n'
    
    return markers_content

def generate_fradius_markers(vertices: List[Vertex], transform_x, transform_y) -> str:
    """生成FRADIUS圆弧标记"""
    fradius_content = ""
    
    for vertex in vertices:
        if vertex.fradius:
            x, y = transform_x(vertex.x), transform_y(vertex.y)
            
            # FRADIUS圆圈标记
            fradius_content += f'<circle cx="{x:.0f}" cy="{y:.0f}" r="4" opacity="1" fill="none" stroke="#FFA500" stroke-width="2"/>\n'
            
            # FRADIUS数值标签
            text_x = x + 10
            text_y = y - 10
            fradius_content += f'<text x="{text_x:.0f}" y="{text_y:.0f}" font-family="Arial" font-size="8" fill="#FFA500">R{vertex.fradius:.0f}</text>\n'
    
    return fradius_content

def generate_coordinate_table(vertices: List[Vertex], canvas_width: int) -> str:
    """生成顶点坐标表"""
    table_x = canvas_width - 290
    table_y = 510
    table_width = 280
    table_height = min(280, 40 + len(vertices) * 12)
    
    table_content = f'<rect x="{table_x}" y="{table_y}" width="{table_width}" height="{table_height}" fill="white" stroke="#333" stroke-width="1" opacity="0.95" rx="5"/>\n'
    
    # 表头
    table_content += f'<text x="{table_x + table_width//2}" y="{table_y + 15}" text-anchor="middle" font-family="Arial" font-size="12" font-weight="bold" fill="#333">顶点坐标表</text>\n'
    
    # 列标题
    table_content += f'<text x="{table_x + 10}" y="{table_y + 30}" font-family="Arial" font-size="10" font-weight="bold" fill="#666">序号</text>\n'
    table_content += f'<text x="{table_x + 50}" y="{table_y + 30}" font-family="Arial" font-size="10" font-weight="bold" fill="#666">X (mm)</text>\n'
    table_content += f'<text x="{table_x + 150}" y="{table_y + 30}" font-family="Arial" font-size="10" font-weight="bold" fill="#666">Y (mm)</text>\n'
    table_content += f'<text x="{table_x + 230}" y="{table_y + 30}" font-family="Arial" font-size="10" font-weight="bold" fill="#666">FRAD</text>\n'
    
    # 分隔线
    table_content += f'<line x1="{table_x + 5}" y1="{table_y + 33}" x2="{table_x + table_width - 5}" y2="{table_y + 33}" stroke="#ccc" stroke-width="1"/>\n'
    
    # 数据行
    for i, vertex in enumerate(vertices):
        if i >= 20:  # 限制显示行数
            break
            
        row_y = table_y + 45 + i * 12
        
        table_content += f'<text x="{table_x + 15}" y="{row_y}" text-anchor="middle" font-family="Arial" font-size="9" fill="#333">{i}</text>\n'
        table_content += f'<text x="{table_x + 55}" y="{row_y}" font-family="Arial" font-size="9" fill="#333">{vertex.x:.2f}</text>\n'
        table_content += f'<text x="{table_x + 155}" y="{row_y}" font-family="Arial" font-size="9" fill="#333">{vertex.y:.2f}</text>\n'
        
        if vertex.fradius:
            table_content += f'<text x="{table_x + 235}" y="{row_y}" font-family="Arial" font-size="9" fill="#FFA500">{vertex.fradius:.1f}</text>\n'
        else:
            table_content += f'<text x="{table_x + 235}" y="{row_y}" font-family="Arial" font-size="9" fill="#666">-</text>\n'
    
    return table_content

# 测试函数
def test_professional_svg():
    """测试专业SVG生成"""
    # 创建示例顶点
    test_vertices = [
        Vertex(0, 0, 0),
        Vertex(1000, 0, 0),
        Vertex(1000, 1000, 0, fradius=500),
        Vertex(0, 1000, 0),
    ]
    
    svg_content = generate_professional_svg(test_vertices, "Test PLOOP Profile", 5700.0)
    
    with open("test_professional.svg", "w", encoding="utf-8") as f:
        f.write(svg_content)
    
    print("测试SVG已生成: test_professional.svg")

if __name__ == "__main__":
    test_professional_svg() 